import { SET_TODO, SET_TODOLIST, REMOVE_TODO, SET_STATUS, SET_DOING } from "@/store/actionTypes"
import { ITodo, TODO_STATUS } from "@/typings"
import { watch } from "vue";
import { Store, useStore } from "vuex"

export interface IUseTodo {

  setTodo: (value: string)=> void;
  setTodoList: ()=> void;
  removeTodo: (id: number)=> void;
  setStatus: (id: number)=> void;
  setDoing: (id: number)=> void;
}

interface IUseLocalStorage {

  getLocalStorage: ()=> ITodo[],
  setLocalStorage: (todoList: ITodo[])=> void,
}


function useTodo (): IUseTodo {

  const store: Store<any> = useStore();
  
  const { getLocalStorage, setLocalStorage }: IUseLocalStorage = useLocalStorage();
  const todoList: ITodo[] = getLocalStorage();

  /**
   * 使用v3 composition API
   * watch 监听
   *  只要list改变，那就更新LocalStorage
   */ 
  watch(() => {
    return store.state.list;
  }, (todoList) => {
    setLocalStorage(todoList);
  })


  /**
   * 设置列表
   */
  function setTodo (value: string): void {
    const todo: ITodo = {
      id: new Date().getTime(),
      content: value,
      status: TODO_STATUS.WILLDO
    }

    store.dispatch(SET_TODO, todo); 
  }


  function setTodoList () {
    store.dispatch(SET_TODOLIST, todoList);
    console.log(store.state.list);
  }

  function removeTodo (id: number): void {
    console.log('removeTodo');
    store.dispatch(REMOVE_TODO, id)  
  }

  /**
   * 设置状态
   */ 
  function setStatus (id: number): void {
    console.log('setStatus');
    store.dispatch(SET_STATUS, id);
  }

  function setDoing (id: number): void {
    console.log('setDoing');
    store.dispatch(SET_DOING, id);
  }

  return {
    setTodo,
    setTodoList,
    removeTodo,
    setStatus,
    setDoing,
  }
}

function useLocalStorage (): IUseLocalStorage {
  
  function getLocalStorage (): ITodo[] {
    return JSON.parse(localStorage.getItem('todoList') || '[]');
  }

  function setLocalStorage (todoList: ITodo[]): void {
    localStorage.setItem('todoList', JSON.stringify(todoList))
  }

  return {
    getLocalStorage,
    setLocalStorage
  }
}

export {
  useTodo,
  useLocalStorage
}